package com.api.devices.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class SafeHexReader {
    private static String filePath = "D:\\Project\\demo\\20250515210200.dat";
    public static void main(String[] args) {
//        String filePath = "data.dat";

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            br.readLine(); // 跳过第一行

            String line;
            while ((line = br.readLine()) != null) {
                // 过滤非HEX字符（只保留0-9, A-F, a-f）
                System.out.println("line:"+line);
                String cleanHex = line.replaceAll("[^0-9A-Fa-f]", "");

                if (!cleanHex.isEmpty()) {
                    try {
                        byte[] bytes = hexStringToBytes(cleanHex);
                        System.out.println("Valid HEX: " + cleanHex);
                    } catch (NumberFormatException e) {
                        System.err.println("Invalid HEX in cleaned string: " + cleanHex);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static byte[] hexStringToBytes(String hex) {
        if (hex.length() % 2 != 0) {
            hex = "0" + hex;
        }

        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < hex.length(); i += 2) {
            String byteStr = hex.substring(i, i + 2);
            bytes[i/2] = (byte) Integer.parseInt(byteStr, 16);
        }
        return bytes;
    }
}